#!/usr/bin/env python

# copyright 2010 Studio Cypher, LLC
# developer: Will Emigh
# projects@studiocypher.com

# Custom modules
from authentication import user_required
from authentication import get_account_from_user
from models import Account
from models import DestinationRecord
from models import Planet
from models import ColonyShip
from models import RecyclingShip
from models import FreighterShip
from models import Log

# Built-in or Google modules
import cgi
import os
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users


from google.appengine.ext import db





        
class CalculateCost(webapp.RequestHandler):
    def post(self):
        user = users.get_current_user()

        # If they don't already have an account, redirect to main
        account = get_account_from_user(user)
        if (account == None):
            self.redirect("/")
            return
        
        ship_type = self.request.get("ship_type")

        if( ship_type == "colony"):
            ship_id = self.request.get("ship_id1")
        elif( ship_type == "recycling"):
            ship_id = self.request.get("ship_id2")
        else:
            ship_id = self.request.get("ship_id3")
            
        if( ship_id ):    
            dest_id = self.request.get("destination")
            destination = db.get(dest_id)

            cost = account.current_planet.get_distance(destination)

            dest_rec = DestinationRecord(destination=destination, cost=cost, ship_type=ship_type, ship=ship_id)
            dest_rec.put()
        else:
            dest_rec = None
            cost = 0
            destination = None
            
        solar_system = Planet.all()
        error_msg = []
        colony_ships = None
        recycler_ships = None
        freighter_ships = None
        all_ships = ColonyShip.all()
        colony_ships = all_ships.filter('owner =',account).filter('planet =', account.current_planet)
        all_ships = RecyclingShip.all()
        recycler_ships = all_ships.filter('owner =',account).filter('planet =', account.current_planet)
        all_ships = FreighterShip.all()
        freighter_ships = all_ships.filter('owner =',account).filter('planet =', account.current_planet)
        colony_cnt = colony_ships.count()
        recycler_cnt = recycler_ships.count()
        freighter_cnt = freighter_ships.count()
        
        """
        colony = None
        for colony_key in account.current_planet.colonies :
            colony = db.get(colony_key)
            if( colony.owner == account ):
                break;
        """
        msg = "the calculated move cost: " + str(cost) + "<br />"
        Log.log(account.email, msg, "", "")
        
        template_values = {'account': account,
                           'current_planet': account.current_planet,
                           'colony_ships': colony_ships,
                           'colony_cnt': colony_cnt,
                           'recycler_ships': recycler_ships,
                           'recycler_cnt': recycler_cnt,
                           'freighter_cnt': freighter_cnt,
                           'freighter_ships': freighter_ships,
                           'solar_system': solar_system,
                           'destination': destination,
                           'dest_rec': dest_rec,
                           'cost': cost
                           }
        
        path = os.path.join(os.path.dirname(__file__), 'solar_system.html')
        self.response.out.write(template.render(path, template_values))       

                    
application = webapp.WSGIApplication(
                                     [('/calculate/move/', CalculateCost)],
                                     debug=True)									 
def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
